package rsj.api.account.entity;

import com.alibaba.fastjson.annotation.JSONField;
import common.statusenum.BillingEnum;
import common.statusenum.ServiceStatusEnum;
import common.statusenum.StatusEnum;
import lombok.Data;
import org.springframework.util.CollectionUtils;
import rsj.api.contract.entity.Contract;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 财务信息
 *
 * @author yuanqinglong
 * @since 2021/7/15 10:37
 */
@Data
public class Finance {

    /**
     * 客户编号
     */
    private String custId;
    /**
     * 合同id
     */
    private String orgpId;
    /**
     * 机构id
     */
    private String orgId;
    /**
     * 客户简称
     */
    private String custSname;
    /**
     * 账号标识
     */
    private String autKeyid;
    /**
     * 当前状态
     */
    private String orgpStatus;
    /**
     * 剩余量
     */
    private String remainder;
    /**
     * 有效期
     */
    private String validPeriod;
    /**
     * 更新时间
     */
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTm;
    /**
     * 批次详情状态（0=无合同，1=有合同）
     */
    private String haveContract;
    /**
     * 账号状态（0=停用，1=启用）
     */
    private String userStatus;


    /**
     * 处理服务有效期
     *
     * @param organizeContracts 组织合同
     */
    public void processingServiceValidityPeriod(List<Contract> organizeContracts) {
        String getOrgpStatus = Optional.ofNullable(getOrgpStatus()).orElse("");
        haveContract = CollectionUtils.isEmpty(organizeContracts) ? StatusEnum.NO.getCode() : StatusEnum.YES.getCode();
        switch (getOrgpStatus) {
            case ServiceStatusEnum.IN_SERVICE_CODE:
            case ServiceStatusEnum.ON_TRIAL_CODE:
            case ServiceStatusEnum.LOW_SPEED_CODE:
                // 计算服务中、试用中、限速的 合同有效期剩余天最少
                organizeContracts = organizeContracts.stream().filter(this::serviceStatusContract).collect(Collectors.toList());
                // Objects.equals(contract.getOrgpBillmethod(), BillingEnum.COMBINATION_BILLING_CODE) 包量合同才计算剩余数
                // 非包量合同过滤后 为空集合 下面代码执行结果为 "-"
                List<Contract> remainingAmount = organizeContracts.stream().filter(contract -> Objects.equals(contract.getOrgpBillmethod(), BillingEnum.COMBINATION_BILLING_CODE)).collect(Collectors.toList());
                Integer remainderCalc = remainingAmount.stream().map(contract -> (contract.getOrgpBuyamount() - contract.getOrgpUseamount())).min(Integer::compareTo).orElse(null);
                this.remainder = Optional.ofNullable(remainderCalc).map(String::valueOf).orElse("-");
                // 计算剩余天数
                Long daysCalc = organizeContracts.stream().map(contract -> contract.getOrgpEndtime().toEpochDay() - LocalDate.now().toEpochDay()).min(Long::compareTo).orElse(null);
                validPeriod = Optional.ofNullable(daysCalc).map(String::valueOf).orElse("-");
                break;
            // 试用到期、服务到期显示已到期
            case ServiceStatusEnum.TRIAL_EXPIRES_CODE:
            case ServiceStatusEnum.SERVICE_EXPIRATION_CODE:
                setRemainder("已到期");
                setValidPeriod("已到期");
                break;
            default:
                setRemainder("-");
                setValidPeriod("-");
                setHaveContract(StatusEnum.NO.getCode());
                break;
        }
        orgpStatus = Optional.ofNullable(orgpStatus).orElse("-");
    }


    /**
     * 服务状态的合同
     *
     * @param contract 合同
     * @return boolean
     */
    private boolean serviceStatusContract(Contract contract) {
        return Objects.equals(contract.getOrgpStatus(), ServiceStatusEnum.IN_SERVICE_CODE)
                || Objects.equals(contract.getOrgpStatus(), ServiceStatusEnum.ON_TRIAL_CODE)
                || Objects.equals(contract.getOrgpStatus(), ServiceStatusEnum.LOW_SPEED_CODE);
    }
}
